//
//  GeneralManagerViewController.m
//  Wallets Manager
//
//  Created by Tung Nguyen on 9/26/12.
//  Copyright (c) 2012 BKHN. All rights reserved.
//

#import "GeneralManagerViewController.h"

@interface GeneralManagerViewController ()
{
    CustomAlertView *alertView;
}
@end

@implementation GeneralManagerViewController
@synthesize scrollView;
@synthesize backButton;
@synthesize popUpView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.tabBarItem.image = [UIImage imageNamed:@"money-01.png"];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    //----Test notification //
    [AJNotificationView showNoticeInView:self.view
                                    type:AJNotificationTypeBlue
                                   title:@"Plan A has Complete"
                         linedBackground:AJLinedBackgroundTypeDisabled
                               hideAfter:3.0f];
    
    scrollView.contentSize = CGSizeMake(640, 80);
    scrollView.delegate = self;
    

    
    //------------------------Init Table View-----------------------------//
    //------Data Section Key : Key for group of expense and income 
    dateSectionKey = [[NSMutableArray alloc]init];
    //------Income Expense Dictionary : Dictionary With Two Array Expense and Icome Group by their day key----//
    
    
    NSCalendar *cal = [NSCalendar currentCalendar];
    
    NSDate *date = [NSDate date];
    NSDateComponents *comps = [cal components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit)
                                     fromDate:date];
    [comps setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
    today = [cal dateFromComponents:comps];
    
    //Get Income and Expense Array
    folyAppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    incomeArray = [DataBaseAccess getAllIncomeByDate:delegate.currentWallet andDate:today];
    incomeRowNumber = [incomeArray count];
    expenseArray = [DataBaseAccess getAllExpenseByDate:delegate.currentWallet andDate:today];
    expenseRowNumber = [expenseArray count];
    //---------------KODAK------------------
    loanArray = [DataBaseAccess getAllLoanEventsInWallet:delegate.currentWallet inTimeFrom:today];
    loanRowNumber = [loanArray count];
    debtArray = [DataBaseAccess getAllDebtEventsInWallet:delegate.currentWallet inTimeFrom:today];
    debtRowNumber = [debtArray count];

    
    //------------------Add Income Expense Table View + Footer-----------------//
    incomeExpenseTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 90, 320, 130) style:UITableViewStylePlain];
    incomeExpenseTableView.delegate = self;
    incomeExpenseTableView.dataSource = self;
    incomeExpenseTableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:incomeExpenseTableView];
    
    incomeExpenseLoadMoreButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [incomeExpenseLoadMoreButton setImage:[UIImage imageNamed:@"footer_button.png"] forState:UIControlStateNormal];
    incomeExpenseLoadMoreButton.frame = CGRectMake(0, 220, 320, 30);
    incomeExpenseLoadMoreButton.backgroundColor = [UIColor clearColor];
    [incomeExpenseLoadMoreButton addTarget:self action:@selector(icEpenseLoadMoreButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:incomeExpenseLoadMoreButton];
    [self.view bringSubviewToFront:incomeExpenseLoadMoreButton];
    //-----------------------------------------------------------------------//
    
    //---------------KODAK------------------
    //------------------Add Loan Debt Table View + Footer-----------------//
    loanDebtTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 260, 320, 130) style:UITableViewStylePlain];
    loanDebtTableView.delegate = self;
    loanDebtTableView.dataSource = self;
    loanDebtTableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:loanDebtTableView];
    
    loanDebtLoadMoreButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [loanDebtLoadMoreButton setImage:[UIImage imageNamed:@"footer_button.png"] forState:UIControlStateNormal];
    loanDebtLoadMoreButton.frame = CGRectMake(0, 390, 320, 30);
    loanDebtLoadMoreButton.backgroundColor = [UIColor clearColor];
    [loanDebtLoadMoreButton addTarget:self action:@selector(loanDebtLoadMoreButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:loanDebtLoadMoreButton];
    [self.view bringSubviewToFront:loanDebtLoadMoreButton];
    //-----------------------------------------------------------------------//

    [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(scrollViewPageChanged) userInfo:nil repeats:YES];
    
    //---------------------------NSNotification Center----------------------//
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(alertViewIncomePressed :) name:@"alertViewIncomePressed" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(alertViewExpensePressed :) name:@"alertViewExpensePressed" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(alertViewReceivePressed :) name:@"alertViewReceivePressed" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(alertViewPayPressed :) name:@"alertViewPayPressed" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadIncomeExpenseTable :) name:@"reloadIncomeExpenseTable" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addExpense_OnSuccess :) name:@"addExpense_OnSuccess" object:nil];
    
    //---------------KODAK------------------
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadLoanDebtTable:) name:@"reloadLoanDebtTable" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(planCompleted : ) name:@"planCompleted" object:nil];
    // Do any additional setup after loading the view from its nib.
}

-(void)viewWillAppear:(BOOL)animated {
    //[self viewDidLoad];
}
- (void)viewDidUnload
{
    [self setScrollView:nil];
    [self setPopUpView:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - IBAction Delegate
- (IBAction)backButtonPressed:(id)sender {
   folyAppDelegate *myDelegate =   (folyAppDelegate *)[[UIApplication sharedApplication]delegate];
    [myDelegate.navigationController popViewControllerAnimated:YES];
    
}

- (IBAction)addButtonPressed:(id)sender {
    alertView = [[CustomAlertView alloc]initWithNibName:@"CustomAlertView" bundle:nil];
    
    [self.view addSubview:alertView.view];
    NSLog(@"%@", [self.view subviews]);
}

- (IBAction)editButtonPressed:(id)sender {
    if(currentIndexPath.row < incomeRowNumber) {
        AddIncomeViewController *addIncomeView = [[AddIncomeViewController alloc]init];
        addIncomeView.kindOfView = @"Edit";
        addIncomeView.currentIncome = currentIncome;
        [self.navigationController pushViewController:addIncomeView animated:YES];
    } else {
        AddExpenseViewController *addExpenseView = [[AddExpenseViewController alloc]init];
        addExpenseView.kindOfView = @"Edit";
        addExpenseView.currentExpense = currentExpense;
        [self.navigationController pushViewController:addExpenseView animated:YES];
    }
    [popup dismissModal];
    
}

- (IBAction)deleteButtonPressed:(id)sender {
    if(currentIndexPath.row < incomeRowNumber) {
        [DataBaseAccess deleteIncome:[incomeArray objectAtIndex:currentIndexPath.row]];
        [incomeArray removeObjectAtIndex:currentIndexPath.row];
      
    } else {
        [DataBaseAccess deleteExpense:[expenseArray objectAtIndex:currentIndexPath.row -incomeRowNumber]];
        [expenseArray removeObjectAtIndex:currentIndexPath.row-incomeRowNumber];
    }
    
    [popup dismissModal];
      [incomeExpenseTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:currentIndexPath] withRowAnimation:UITableViewRowAnimationMiddle];
}

- (IBAction)viewButtonPressed:(id)sender {
    if(currentIndexPath.row < incomeRowNumber) {
        ViewIncomeViewController *viewIncomeViewController = [[ViewIncomeViewController alloc]init];
        viewIncomeViewController.currentIncome = currentIncome;
        [self.navigationController pushViewController:viewIncomeViewController animated:YES];
    } else {
        ViewExpenseViewController *viewExpenseViewController = [[ViewExpenseViewController alloc]init];
        viewExpenseViewController.currentExpense = currentExpense;
        [self.navigationController pushViewController:viewExpenseViewController animated:YES];
    }
    
    [popup dismissModal];
}

-(void) icEpenseLoadMoreButtonPressed{
    IncomeExpenseDetailViewController *detailViewController = [[IncomeExpenseDetailViewController alloc]init];
    
    self.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:detailViewController animated:YES];
    
    self.hidesBottomBarWhenPushed = NO;
}

//---------------KODAK------------------
-(void) loanDebtLoadMoreButtonPressed{
    
    IncomeExpenseDetailViewController *detailViewController = [[IncomeExpenseDetailViewController alloc]init];
    
    self.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:detailViewController animated:YES];
    
    self.hidesBottomBarWhenPushed = NO;
}
#pragma mark - ScrollView Delegate
- (void) scrollViewPageChanged {
    
    CGRect currentFrame = scrollView.frame;
    if(currentFrameIndex == 0) {
        currentFrameIndex = 1;
        currentFrame.origin.x = 320;
        currentFrame.origin.y = 0;
    } else {
        currentFrameIndex = 0;
        currentFrame.origin.x = 0;
        currentFrame.origin.y = 0;
    }
    
    [scrollView scrollRectToVisible:currentFrame animated:YES] ;
}

#pragma mark - Notification Center Delegate
- (void) alertViewIncomePressed : (NSNotification *) notification {
    AddIncomeViewController *addIncomeViewController = [[AddIncomeViewController alloc]init];
    addIncomeViewController.kindOfView = @"Add";
    [self.navigationController pushViewController:addIncomeViewController animated:YES];
}

- (void) alertViewExpensePressed : (NSNotification *) notification {
    AddExpenseViewController *addExpenseViewController = [[AddExpenseViewController alloc]init];
    addExpenseViewController.kindOfView = @"Add";
    [self.navigationController pushViewController:addExpenseViewController animated:YES];
}

-(void) alertViewReceivePressed : (NSNotification*) notification {
    AddLoanViewController *addLoanViewController = [[AddLoanViewController alloc]init];
    addLoanViewController.kindOfView = @"Add";
    [self.navigationController pushViewController:addLoanViewController animated:YES];
}

-(void) alertViewPayPressed : (NSNotification*) notification {
    AddDebtViewController *addDebtViewController = [[AddDebtViewController alloc]init];
    addDebtViewController.kindOfView = @"Add";
    [self.navigationController pushViewController:addDebtViewController animated:YES];
}

-(void)reloadIncomeExpenseTable: (NSNotification*)notification {
    //folyAppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    //allDateSection = [DataBaseAccess getAllDate:delegate.currentWallet];
    folyAppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    incomeArray = [DataBaseAccess getAllIncomeByDate:delegate.currentWallet andDate:today];
    incomeRowNumber = [incomeArray count];
    expenseArray = [DataBaseAccess getAllExpenseByDate:delegate.currentWallet andDate:today];
    expenseRowNumber = [expenseArray count];
    
    [incomeExpenseTableView reloadData];
    
    
}

-(void) planCompleted : (NSNotification*) notification {
    [AJNotificationView showNoticeInView:self.view
                                    type:AJNotificationTypeBlue
                                   title:[NSString stringWithFormat:@"Congratulation ! \n %@ has completed",(NSString*)[notification object]]
                         linedBackground:AJLinedBackgroundTypeDisabled
                               hideAfter:3.0f];
}

-(void) addExpense_OnSuccess : (NSNotification*)notification {
    folyAppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    incomeArray = [DataBaseAccess getAllIncomeByDate:delegate.currentWallet andDate:today];
    incomeRowNumber = [incomeArray count];
    expenseArray = [DataBaseAccess getAllExpenseByDate:delegate.currentWallet andDate:today];
    expenseRowNumber = [expenseArray count];
    
    [incomeExpenseTableView reloadData];
}
#pragma mark - Table View Delegate

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//    folyAppDelegate *delegate = [[UIApplication sharedApplication]delegate];
//    
//    NSMutableArray *incomeArray = [DataBaseAccess getAllIncomeByDate:delegate.currentWallet andDate:today];
//    NSMutableArray *expenseArray = [DataBaseAccess getAllExpenseByDate:delegate.currentWallet andDate:today];
//    NSLog(@"Number of row %d",[incomeArray count]+[expenseArray count]);
    return  [incomeArray count]+[expenseArray count];
}

-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {

    return  1;
}
-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}

-(UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView * headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0,320,30)];
    headerView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"sub_navbar_bg.png"]];
    //-------------------Format Date Section --------------------//
    
    
    UILabel *sectionTitleLabel = [[UILabel alloc]initWithFrame:CGRectMake(5, 0, 200, 20)];
    if(tableView == incomeExpenseTableView){
        sectionTitleLabel.text = @"Income & Expense Diary";
    } else {
        sectionTitleLabel.text = @"Loan & Debt Diary";
    }
        
    
    sectionTitleLabel.textColor = [UIColor whiteColor];
    sectionTitleLabel.font = [UIFont systemFontOfSize:14];
    sectionTitleLabel.backgroundColor = [UIColor clearColor];
    [headerView addSubview:sectionTitleLabel];
    
    return headerView;
}

-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellInditifier = @"CellInditifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellInditifier] ;
    
    UIImageView *imageView;
    UILabel *titleLabel;
    UITextField *amountTextField;
    
    
    
    if( cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellInditifier];
        
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 5, 40, 40)];
        imageView.backgroundColor = [UIColor clearColor];
        imageView.tag = 100;
        [cell addSubview:imageView];
        
        titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(50, 10, 200, 20)];
        titleLabel.backgroundColor = [UIColor clearColor];
        titleLabel.textColor = [UIColor colorWithRed:99.0/255.0 green:182.0/255.0 blue:67.0/255.0 alpha:1];
        titleLabel.tag = 200;
        [cell addSubview:titleLabel];
        
        amountTextField = [[UITextField alloc]initWithFrame:CGRectMake(0, 10, 280, 20)];
        amountTextField.textColor = [UIColor whiteColor];
        amountTextField.backgroundColor = [UIColor clearColor];
        amountTextField.font = [UIFont systemFontOfSize:12];
        amountTextField.tag = 300;
        amountTextField.enabled = NO;
        [cell addSubview:amountTextField];
    }
    
    imageView = (UIImageView*) [cell viewWithTag:100];
    titleLabel = (UILabel*) [cell viewWithTag:200];
    amountTextField = (UITextField*)[cell viewWithTag:300];
    
    if( indexPath.row < [incomeArray count]) {
        Income *tempIncome = [incomeArray objectAtIndex:indexPath.row];
        NSLog(@"%@",tempIncome.i_name);
        titleLabel.text = tempIncome.i_name;
        imageView.image = [UIImage imageNamed:tempIncome.iToIncomeType.it_image];
        
        amountTextField.text = [NSString stringWithFormat:@"%d",[tempIncome.i_amount intValue]];
        amountTextField.borderStyle = UITextBorderStyleRoundedRect;
        amountTextField.backgroundColor = [UIColor colorWithRed:14.0/255.0 green:154.0/255.0 blue:209.0/255.0 alpha:1];

    } else {
        NSLog(@"indexPath.row = %d",indexPath.row);
        Expense *tempExpense = [expenseArray objectAtIndex:indexPath.row - [incomeArray count]];
        titleLabel.text = tempExpense.e_name;
        imageView.image = [UIImage imageNamed:tempExpense.eToExpenseType.et_image];

        amountTextField.text = [NSString stringWithFormat:@"-%d",[tempExpense.e_amount intValue]];
        amountTextField.borderStyle = UITextBorderStyleRoundedRect;
        amountTextField.backgroundColor = [UIColor colorWithRed:202.0/255.0 green:62.0/255.0 blue:62.0/255.0 alpha:1];
    }
    
    CGSize amountTextFieldSize = [amountTextField.text sizeWithFont:[UIFont systemFontOfSize:12]];
    amountTextField.frame = CGRectMake(290-amountTextFieldSize.width,10 , amountTextFieldSize.width+15, 20);
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    currentIndexPath = indexPath;
    CGRect rectOfCellInTableView = [tableView rectForRowAtIndexPath:indexPath];
    CGRect rectOfCellInSuperview = [tableView convertRect:rectOfCellInTableView toView:[tableView superview]];
    
   
    NSLog(@"%f %f",rectOfCellInSuperview.origin.x,rectOfCellInSuperview.origin.y);
    if(indexPath.row <incomeRowNumber) {
        currentIncome = [incomeArray objectAtIndex:indexPath.row];
    } else {
        currentExpense = [expenseArray objectAtIndex:indexPath.row-incomeRowNumber];
    }
    
    
    
    if (popup == nil) {
        popup = [[SNPopupView alloc] initWithContentView:popUpView contentSize:CGSizeMake(170, 60)];
		
        [popup presentModalAtPoint:CGPointMake(rectOfCellInSuperview.origin.x, rectOfCellInSuperview.origin.y +50) inView:self.view animated:YES];
		
		[popup addTarget:self action:@selector(didTouchPopupView:)];
		//[popup release];
		[popup setDelegate:self];
	}
	else if (NO) {
		[popup dismiss:YES];
		popup = nil;
	}
}

#pragma mark -----------------Popup-----------------
- (void)didTouchPopupView:(SNPopupView*)sender {
    //	DNSLogMethod
    //	DNSLog(@"%@", sender);
}



- (void)didDismissModal:(SNPopupView*)popupview {
	//DNSLogMethod
	if (popupview == popup) {
		popup = nil;
	}
}


@end
